<?php

namespace App\Http\Controllers\Api;

use App\Api\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Models\MUser;
use App\Models\MUserCash;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class WeChatLoginController extends ApiController
{
    public function __construct()
    {
        $this->config =[
            'app_id' =>'wxc31bdf2ce95010be',
            'secret' =>'94e8c1e47f2371633346efe807c7da2b',
            'response_type' => 'array',
        ];
        $this->scopes = ['snsapi_userinfo'];//snsapi_base
        $this->app = Factory::officialAccount($this->config);

    }

    /**
     * @param Request $request
     */
    public function wx_login(){

//        $appid='wxc31bdf2ce95010be'; //测试账户的appid
//        $redirect_uri = urlencode ( 'http://www.fgehua.com/h5');
//        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
//        return $this->ReturnMessage(200,getMessage(),$url);

//        $appid='wxe8dbaf4ab86f0441'; //测试账户的appid
//        $redirect_uri = urlencode (route('getUser') );
//        $url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
//        return $this->ReturnMessage('200','获取成功',$url);

        $url = env('APP_URL') . '/h5?pid=555';
        $response = $this->app->oauth->scopes($this->scopes)
//            ->redirect('http://www.fgehua.com/h5?pid=555');
            ->redirect($url);
        return $response;
    }
    function getUser(Request $request){
        $appid = "wxc31bdf2ce95010be";
        $secret = "94e8c1e47f2371633346efe807c7da2b";
        $code = $_GET["code"];
        dump($request->all());die;
//第一步:取全局access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $token =$this-> getJson($url);
//第二步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = $this-> getJson($oauth2Url);

//第三步:根据全局access_token和openid查询用户信息
        $access_token = $token["access_token"];
        $openid = $oauth2['openid'];
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";

        $WeUser = $this-> getJson($get_user_info_url);
        dump($WeUser);die;
        return redirect('http://fgehua.com/h5/');
        $watchid = $WeUser->getId(); //微信授权openid
        $nickname= $WeUser->getNickname(); // 对应微信的 nickname
        $realname= $WeUser->getName(); // 对应微信的 nickname
        $avatar= $WeUser->getAvatar(); // 头像网址
        $user = MUser::where('watchid',$watchid)->first();

        if(!$user){
            $user = new Muser();
            $user->account = get_rand_account();
        }
        $user->watchid = $watchid;
        $user->nickname = $nickname;
        $user->realname  =$realname;
        $user->avatar = $avatar;
        $user->save();
        return ['status'=>'success','code'=>'200','message'=>'授权成功','data'=>$user];
    }
    function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    function is_login(Request $request){
        $header_token= $request->header('token');
        if(!$header_token){
            return response()->json([
                'code' => 201,
                'message' => 'token失效',
            ]);
        }
        $user =MUser::where('token',$header_token)->first();
        if(!$user){
            return response()->json([
                'code' => 201,
                'message' => 'token失效',
            ]);
        }
        $this->data= [
            'status'=>200,
            'msg'=>'授权成功',
            'token'=>$user->token,
            'account'=>$user->account
        ];
        return response()->json($this->data);
    }
    /**
     * @return array
     */
    function login_wx(Request $request){
        $code = $request->get("code", "");
        if ($code === ""){
            $this->data= [
                'status'=>201,
                'msg'=>'请重新获取授权CODE'
            ];
            return response()->json($this->data);
        }

        try{
            DB::transaction(function () use ($request) {
                $pid = $request->pid??0;
                $WeUser = $this->app->oauth->user();
                $watchid = $WeUser->getId(); //微信授权openid
//                $nickname= $WeUser->getNickname(); // 对应微信的 nickname
                $nickname= $this->userTextEncode($WeUser->getNickname()); // 对应微信的 nickname
                $realname= $WeUser->getName(); // 对应微信的 nickname
                $avatar= $WeUser->getAvatar(); // 头像网址
                if($pid >0){ //有推荐人的话 判断推荐人存在
                    $puser = MUser::where('id',$pid)->first();
                    if(!$puser){
                        $this->data= [
                            'status'=>-1,
                            'msg'=>'推荐人不存在'
                        ];
                        return response()->json($this->data);
                    }
                }
                $flash = false;
                $user = MUser::where('watchid',$watchid)->first();
                if(!$user){
                    $user = new Muser();
                    $user->account = get_rand_account();
                }
                $user->watchid = $watchid;
                $user->nickname = $nickname;
                $user->realname  =$realname;
                $user->avatar = $avatar;
                $user->token = md5(get_rand_account().time());
                $flash= $user->save();

                $flash = $flash == true?true:false;
                $relation =DB::table('user_relation')->where('user_id',$user->id)->first();
                if(!$relation&&$pid >0){ // 没有推荐人的话 -建立关系
                    $flash = relationUser($pid,$user->id);
                    $flash = $flash == true?true:false;
                }
                if($flash){
                    $this->data= [
                        'status'=>200,
                        'msg'=>'授权成功',
                        'token'=>$user->token,
                        'account'=>$user->account
                    ];
                } else{
                    DB::rollBack();
                    $this->data= [
                        'status'=>201,
                        'msg'=>'授权失败'
                    ];
                }

            });
        }catch(Exception $e){
            DB::rollBack();
            $this->data= [
                'status'=>201,
                'msg'=>'请重新获取授权CODE'
            ];

        }
        return response()->json($this->data);
    }
    public function userTextEncode($str){
        if(!is_string($str))return $str;
        if(!$str || $str=='undefined')return '';

        $text = json_encode($str); //暴露出unicode
        $text = preg_replace_callback("/(\\\u[ed][0-9a-f]{3})/i",function($str){
            return addslashes($str[0]);
        },$text); //将emoji的unicode留下，其他不动，这里的正则比原答案增加了d，因为我发现我很多emoji实际上是\ud开头的，反而暂时没发现有\ue开头。
        return json_decode($text);
    }
    function test(){

        $url =$this->app->url->shorten('https://easywechat.com');
       dump($url);
        $flash = relationUser(31,23);
    }
}